<template>
  <PageWrapper v-loading="loadingRef" contentFullHeight fixedHeight dense>
    <AdVxeTable
      @register="registerTable"
      @checkbox-change="
        () => {
          hasRowSelected = getSelectedRows()?.length > 0;
        }
      "
    >
      <template #tools>
        <Authority :value="'Root.Admin.Identity.LoginLog.Delete'">
          <a-button
            type="primary"
            color="error"
            :disabled="!hasRowSelected"
            @click="handleDeleteBatch"
          >
            <Icon icon="ant-design:delete-outlined" />{{ t('common.delText') }}
          </a-button>
        </Authority>
      </template>
      <template #actionCol="{ row }">
        <TableAction
          outside
          :actions="[
            {
              icon: 'clarity:details-line',
              tooltip: t('common.detailText'),
              onClick: handleReadDetail.bind(null, row),
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              tooltip: t('common.delText'),
              auth: 'Root.Admin.Identity.LoginLog.Delete', // 权限控制
              // ifShow: (_action) => {
              //   return row.Deletable === true; // 根据业务控制是否显示: 是否可删除的数据权限状态
              // },
              popConfirm: {
                title: t('common.delConfirmText'),
                placement: 'left',
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </AdVxeTable>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { ref, h } from 'vue';

  import { useI18n } from '@/hooks/web/useI18n';
  import { useMessage } from '@/hooks/web/useMessage';

  import Icon from '@/components/Icon/Icon.vue';

  import { PageWrapper } from '@/components/Page';
  import { Authority } from '@/components/Authority';
  import { AdVxeTable, useAdVxeTable, TableAction } from '@/components/AdVxeTable';
  import { FormModeEnum } from '@/enums/formEnum';
  import { readLoginLogs, deleteLoginLogs } from '@/api/identity/admin/loginlog';

  import { columns } from './loginlog.data';

  defineOptions({ name: 'LoginLogPage' });

  const { t } = useI18n();
  const { createConfirm, createMessage } = useMessage();

  const loadingRef = ref(false);
  function openWrapLoading() {
    loadingRef.value = true;
  }
  function closeWrapLoading() {
    loadingRef.value = false;
  }

  const hasRowSelected = ref(false);

  const [registerTable, { getTable, reload, openDetailForm }] = useAdVxeTable({
    id: 'system-login-log-page-table',
    // 表标题呈现器
    title: t('routes.system.loginlog.loginlogList'),
    // 表格数据接口请求对象
    api: readLoginLogs,
    // 详情表单
    detailForm: {
      // 表单标识
      formIndex: 'loginlog_detail',
      // 主键字段
      keyField: 'Id',
      // 详情表单抬头
      title: t('routes.system.loginlog.title'),
    },
    // 表单列信息 BasicColumn[]
    columns,
    // 使用搜索表单
    searchForm: true,
    // 行选择设置
    selection: 'checkbox',
    // 是否带有边框 boolean | default（默认）, full（完整边框）, outer（外边框）, inner（内边框）, none（无边框）
    border: false,
    // 是否显示序号列
    showSeqColumn: true,
    // 表格右侧操作列配置 BasicColumn
    actionColumn: {
      width: 80,
      title: t('common.actionText'),
      fixed: 'right',
      slots: { default: 'actionCol' },
    },
  });

  function getSelectedRows() {
    const $table = getTable();
    if ($table) {
      const rows = $table.getCheckboxRecords();
      return rows;
    }
    return [];
  }
  function clearSelectedRows() {
    const $table = getTable();
    if ($table) {
      $table.clearCheckboxRow();
    }
  }

  /** 查看详情 */
  async function handleReadDetail(record: any) {
    openDetailForm(FormModeEnum.ReadOnly, record);
  }

  /** 处理删除 */
  async function handleDelete(record: any) {
    // console.log(record);
    try {
      openWrapLoading();
      const ajaxResult = await deleteLoginLogs([record.Id]);
      if (ajaxResult.Succeeded) {
        createMessage.success(t('common.successText'));
        reload();
        clearSelectedRows();
      }
    } finally {
      closeWrapLoading();
    }
  }
  /** 处理批量删除 */
  async function handleDeleteBatch() {
    const selectedRows = getSelectedRows();
    if (selectedRows?.length > 0) {
      createConfirm({
        zIndex: 999999999,
        iconType: 'warning',
        title: () => h('span', t('sys.app.logoutTip')),
        content: () => h('span', t('common.delConfirmText')),
        onOk: async () => {
          try {
            openWrapLoading();
            const recordIds = selectedRows.map((item) => {
              return item.Id;
            });
            const ajaxResult = await deleteLoginLogs(recordIds);
            if (ajaxResult.Succeeded) {
              createMessage.success(t('common.successText'));
              await reload();
              clearSelectedRows();
            }
          } finally {
            closeWrapLoading();
          }
        },
      });
    }
  }
</script>
